﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agr.CQRS.Infrastructure.Orm;
using Agr.CQRS.Domain.Events;

namespace Agr.CQRS.Infrastructure.Events
{
    public class DomainEventStorage
    {
        private OrmContext ormContext;

        public DomainEventStorage(OrmContext ormContext)
        {
            this.ormContext = ormContext;
        }

        internal IEnumerable<DomainEvent> GetEventsToRebuildAggregateRootUpToVersion(Guid id, int version)
        {
            IList<StoredDomainEvent> sdevents;

            using (var sitx = ormContext.OpenReadonlySession())
                sdevents = 
                    sitx.UseIn<QueryGetEventsToRebuildAggregate>()
                        .AggregateRootIdIs(id)
                        .UpToVersion(version)
                        .Results();

            return from sde in sdevents select sde.GetEvent();
        }

        internal void Store(IList<DomainEvent> events)
        {
            using (var sitx = ormContext.OpenSession())
            {
                foreach (var ev in events)
                {
                    var sde = new StoredDomainEvent();
                    sde.WrapEvent(ev);
                    sitx.Insert(sde);
                }
                sitx.Commit();
            }
        }

    }
}
